import React, {useMemo} from 'react';
import {Animated, Text, Easing} from 'react-native';
import {useDidMount, viewportWidth} from '@/utils/index';
import {IBarrage} from '.';

interface IProps {
  data: IBarrage;
  outside: (data: IBarrage) => void;
}

const Item: React.FC<IProps> = props => {
  const {data, outside} = props;
  const translateX = useMemo(() => new Animated.Value(0), []);
  const width = data.title.length * 15; //弹幕长度，计算偏移出屏幕后删除宽度
  useDidMount(() => {
    Animated.timing(translateX, {
      toValue: 10,
      duration: 6000,
      useNativeDriver: true,
      easing: Easing.linear,
    }).start(({finished}) => {
      //回调函数   finished为true代表动画结束
      if (finished) {
        outside(data);
      }
    });
    translateX.addListener(({value}) => {
      if (value > 3) {
        data.isFree = true;
      }
    });
  });
  return (
    <Animated.View
      style={{
        position: 'absolute',
        top: data.trackIndex * 30,
        transform: [
          {
            translateX: translateX.interpolate({
              inputRange: [0, 10], //动画过程
              outputRange: [viewportWidth, -width], //初始值 到结束
            }),
          },
        ],
      }}>
      <Text>{data.title}</Text>
    </Animated.View>
  );
};

export default Item;
